﻿namespace MicroCloud.AspNetCore
{
    /// <summary>
    /// HttpContext扩展方法
    /// </summary>
    public static class HttpContextExtensions
    {
        #region "扩展方法 - HttpRequest"
        #region "确定指定的 HTTP 请求是否为 AJAX 请求"
        /// <summary>
        /// 确定指定的 HTTP 请求是否为 AJAX 请求
        /// </summary>
        /// <param name="request">HTTP 请求</param>
        /// <returns>如果指定的 HTTP 请求是 AJAX 请求，则为 true；否则为 false</returns>
        public static bool IsAjaxRequest(this HttpRequest request)
        {
            Check.NotNull(request, nameof(request));

            return string.Equals(request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal)
                || string.Equals(request.Headers.XRequestedWith, "XMLHttpRequest", StringComparison.Ordinal);
        }
        #endregion
        #region "确定指定的 HTTP 请求的 ContextType 是否为 Json 方式"
        /// <summary>
        /// 确定指定的 HTTP 请求的 ContextType 是否为 Json 方式
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsJsonContextType(this HttpRequest request)
        {
            Check.NotNull(request, nameof(request));
            bool flag = request.Headers?.ContentType.ToString().IndexOf("application/json", StringComparison.OrdinalIgnoreCase) > -1
                        || request.Headers?.ContentType.ToString().IndexOf("text/json", StringComparison.OrdinalIgnoreCase) > -1;
            if (flag)
            {
                return true;
            }
            flag = request.Headers?.Accept.ToString().IndexOf("application/json", StringComparison.OrdinalIgnoreCase) > -1
                    || request.Headers?.Accept.ToString().IndexOf("text/json", StringComparison.OrdinalIgnoreCase) > -1;
            return flag;
        }
        #endregion
        #region "获取 <see cref="HttpRequest"/> 的用户代理"
        /// <summary>
        /// 获取 <see cref="HttpRequest"/> 的用户代理
        /// </summary>
        /// <param name="request">请求信息</param>
        /// <returns></returns>
        public static string UserAgent(this HttpRequest request)
        {
            Check.NotNull(request, nameof(request));

            var userAgent = request.Headers?.UserAgent.FirstOrDefault();
            return userAgent;
        }
        #endregion
        #region "获取 <see cref="HttpRequest"/> 的请求数据"
        /// <summary>
        /// 获取 <see cref="HttpRequest"/> 的请求数据
        /// </summary>
        /// <param name="request">请求信息</param>
        /// <param name="key">要获取数据的键名</param>
        /// <returns></returns>
        public static string Params(this HttpRequest request, string key)
        {
            Check.NotNull(request, nameof(request));

            if (request.Query.ContainsKey(key))
            {
                return request.Query[key];
            }
            if (request.HasFormContentType)
            {
                return request.Form[key];
            }
            return null;
        }
        #endregion
        #region "获取 <see cref="HttpRequest"/> 的Body请求参数"
        /// <summary>
        /// 获取 <see cref="HttpRequest"/> 的Body请求参数
        /// </summary>
        /// <param name="request">请求信息</param>
        /// <param name="indented">是否缩进</param>
        /// <returns></returns>
        public static string BodyArguments(this HttpRequest request, bool indented = false)
        {
            Check.NotNull(request, nameof(request));

            Stream straem = request.Body;
            Encoding encoding = Encoding.UTF8;
            using StreamReader reader = new(straem, encoding);
            //data就是post传过来的值json格式
            var data = reader.ReadToEndAsync().Result;
            if (indented)
            {
                data = data.ToModel<object>().ToJsonString();
            }
            return data;
        }
        #endregion

        #region "获取 <see cref="HttpRequest"/> 的请求语言集合"
        /// <summary>
        /// 获取 <see cref="HttpRequest"/> 的请求语言集合
        /// </summary>
        /// <param name="request">请求信息</param>
        /// <returns></returns>
        public static string[] AcceptLanguages(this HttpRequest request)
        {
            return request.GetTypedHeaders()
                .AcceptLanguage
                ?.OrderByDescending(x => x.Quality ?? 1)    //质量定义了从0到1的优先级，其中1是最高优先级。Quality defines priority from 0 to 1, where 1 is the highest.
                .Select(x => x.Value.ToString())
                .ToArray() ?? [];
        }
        #endregion

        #endregion

        #region "扩展方法 - HttpContext"
        #region "获取客户端IP地址"
        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetClientIp(this HttpContext context)
        {
            string ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress.ToString();
            }
            return ip;
        }
        #endregion

        #endregion

    }

}